// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
    const {
        userInfo: {
            openid,
            username,
            avatarUrl,
            backImg
        }
    } = event
    let result = undefined;
    try {
        const data = await db.collection('user').where({
            openid: _.eq(openid)
        }).get()
        const {
            url
        } = data.data[0].backImg
        const delImgResult = await cloud.deleteFile({
            fileList: [url]
        })
        result = await db.collection('user').where({
            openid: _.eq(openid)
        }).update({
            data: event.userInfo
        })
    } catch {
        result = await db.collection('user').add({
            data: event.userInfo
        })
    }
    return {
        result
    }
}